import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Text, Radio, ScrollView} from '@tarojs/components'
import {AtSwipeAction, AtSearchBar} from 'taro-ui'
import {ShopList} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {RESOURCE_URL, TARO_ENV} from '../../constants/api'
import {user} from '../../utils/user.service'
import {clearSearch as clearSearchFunc, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import {newHttp} from "../../utils/request";
import Float from "../../components/float/float";
import './index.scss'

type PageOwnProps = {}
type PageState = {
  resource_url: string
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: []
  size: number
  edit: boolean
  frist: boolean
  name: any
  currentIndex: any
}

class Index extends Component {
  state: PageState = {
    resource_url: RESOURCE_URL,
    loadMoreStatus: 'loading',
    list: [],
    size: 10,
    edit: false,
    frist: true,
    name: '',
    currentIndex: 0,
  }
  page = 1

  async UNSAFE_componentWillMount() {
    vcmonitor(this);
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
  }

  async getList() {
    this.page = 1
    const list = await this.getGoods()
    this.setState({list})
  }

  shareParams = ''

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin();
    if (isLogin) {
      this.getList()
    } else {
      user.jumpLogin()
    }
  }

  listEdit() {
    const {list, edit} = this.state
    if (edit) {
      list.map((item) => {
        item['checked'] = false
      })
    }
    this.setState({list, edit: !edit})
  }

  checkAll() {
    const {list, edit} = this.state
    list.map((item) => {
      if (edit) {
        item['checked'] = !item.checked
      }
    })
    this.setState({list})
  }

  jumpedit(uuid) {
    let url = ''
    if (this.state.currentIndex == 0) {
      url = '/common/limited/detail?itemId='
    } else if (this.state.currentIndex == 1) {
      url = '/common/scenic/detail?itemId='
    } else if (this.state.currentIndex == 2) {
      url = '/common/hotel/detail?itemId='
    } else if (this.state.currentIndex == 3) {
      url = '/common/tourist-line/detail?itemId='
    } else if (this.state.currentIndex == 4) {
      url = '/common/product/detail?itemId='
    }

    Taro.navigateTo({
      url: url + uuid
    })
  }

  delcarall(index) {
    const {list} = this.state
    let listnum = 0
    list.map((item) => {
      if (item.checked) {
        listnum++
      }
    })
    if (listnum == 0) {
      Taro.showToast({
        title: '请选择您要删除的商品',
        icon: 'none'
      })
      return false;
    }
    Taro.showModal({
      title: '确认删除',
      content: '确定将你选中的' + listnum + '件商品删除吗？',
      success: async result => {
        if (result.confirm) {
          const idsary = [];
          list.map((item) => {
            if (item.checked) {
              idsary.push(item.id)
            }
          })
          const data = await newHttp.catchPost('/msvc-shop/v1/goods/favorite/update', {
            goods_id: idsary,
            goods_category: this.state.currentIndex
          })
          if (data != false) {
            this.getList()
            Taro.showToast({
              title: '删除成功',
              icon: 'none',
              mask: true
            });
            this.setState({edit: false})
          }
        }
        if (result.cancel) {

        }
      }
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getGoods()
      this.setState({list: [...old, ...newData]})
    }
  }

  checkSelf(index) {
    // edit: true管理状态，false列表状态
    const {list} = this.state
    list[index].checked = !list[index].checked
    this.setState({list})
  }

  delcar(index) {
    const {list} = this.state
    Taro.showModal({
      title: '确认删除',
      content: '您确定删除该商品吗？',
      success: async result => {
        if (result.confirm) {
          Taro.showLoading({title: '删除中', mask: true})
          const id = list[index].id;
          const data = await newHttp.catchPost('/msvc-shop/v1/goods/favorite/update', {
            goods_id: id,
            goods_category: this.state.currentIndex
          })
          if (data != false) {
            this.getList()
            Taro.showToast({
              title: '删除成功',
              icon: 'none',
              mask: true
            });
            this.setState({edit: false})
          }
        }
      }
    })
  }

  async getGoods() {
    this.page, this.state.size
    const params = {
      page: this.page,
      size: this.state.size,
      name: this.state.name,
      goods_category: this.state.currentIndex
    }
    const goodsData = await http.HGet<ShopList[]>('/msvc-shop/v1/goods/favorite/page', params)
    if (goodsData) {
      if (goodsData.currentPage < goodsData.totalPages) {
        this.setState({loadMoreStatus: 'more'})
      } else {
        this.setState({loadMoreStatus: 'noMore'})
      }
      return goodsData.data
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  searchConfirm() {
    this.page = 1
    this.getList()
  }

  input(value) {
    if (value) {
      this.setState({name: value})
    } else {
      clearSearchFunc();
    }
  }

  async clearSearch() {
    await this.setState({name: ''})
    this.getList()
  }

  groupList = [
    {val: 0, label: '限时抢购'},
    {val: 1, label: '景点门票'},
    {val: 2, label: '酒店住宿'},
    {val: 3, label: '旅游线路'},
    {val: 4, label: '普通商品'},
  ]

  categoryListClick(currentIndex) {
    try {
      if (this.state.currentIndex === currentIndex) {
        return false
      }
      Taro.showLoading({title: '加载中...'});
      this.page = 1
      this.setState({currentIndex, loadMoreStatus: 'loading', edit: false}, async () => {
        this.getList()
        Taro.hideLoading()
      })
    } catch (e) {
      Taro.hideLoading()
    }
  }

  render() {
    const {
      currentIndex,
      name,
      loadMoreStatus,
      list,
      edit,
    } = this.state
    return (
      <View className='shopcar-root regional-category'>
        <View className='search-top'>
          <AtSearchBar onConfirm={this.searchConfirm.bind(this)} fixed
            onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
            value={name} onChange={this.input.bind(this)} placeholder='请输入商品名查找'
          />
          <View
            className={`shop-top ${TARO_ENV === 'h5' ? '' : 'shop-top-weapp'} shop-top${process.env.TARO_ENV}`}
          ><View
            className={`shop-top-btn ${TARO_ENV === 'h5' ? '' : 'shop-top-btn-weapp'}`}
            onClick={this.listEdit.bind(this)}
          >{edit ? '完成' : '管理'}</View></View>
        </View>

        {this.groupList.length > 0 &&
          <ScrollView scrollWithAnimation enable-flex scrollX
            className={`scroll-view ${TARO_ENV === 'h5' ? '' : 'scroll-view-weapp'}`}
            style='padding-bottom: 0 !important;'
          >
            <View className={`regional-category-nav ${TARO_ENV === 'h5' ? '' : 'regional-category-nav-weapp'}`}>
              <View></View>
              {
                this.groupList.map((_item, index) => (
                  <View className='regional-category-nav-item' key={index}
                    onClick={this.categoryListClick.bind(this, this.groupList[index].val)}
                  >
                    <View
                      className={`regional-category-nav-item-name ${currentIndex === this.groupList[index].val ? 'active' : ''}`}
                    >{this.groupList[index].label}</View>
                  </View>
                ))
              }
            </View>
          </ScrollView>
        }

        {list.length > 0 && <View className='shopCarBox'>
          {list.map((item, index) =>
            <View className='shopCarlist' key={index}>
              <View className='shopCarlist-box'>
                <View key={item.id}>
                  <AtSwipeAction
                    autoClose
                    options={[
                      {
                        text: '删除',
                        style: {
                          backgroundColor: '#ca0000'
                        }
                      }
                    ]} onClick={this.delcar.bind(this, index)}
                  >
                    <View
                      className={`good-item ${edit ? TARO_ENV !== 'h5' ? 'good-item-edit-weapp' : 'good-item-edit' : ''}`}
                      hoverClass='none'
                    >
                      {edit && <View className='radio-box' onClick={this.checkSelf.bind(this, index)}><Radio
                        checked={item.checked} color='#fe9f00' value={item.gid}
                      /></View>
                      }
                      <View onClick={this.jumpedit.bind(this, item.uuid)} className='good-item-box'>
                        <View className='img-box'>
                          <Image lazyLoad={process.env.TARO_ENV != "h5"}
                            src={RESOURCE_URL + item.poster_background}
                            mode='aspectFill' className='img'
                          />
                        </View>
                        <View className='title-box'>
                          <View className='title'>{item.name}</View>
                          <View className='category-labels'>
                            {item.labels && item.labels.length > 0 && item.labels.map((items, index) => <View
                              className='category-label' key={index}
                            >{items}</View>)}
                          </View>

                          <View className='price'>
                            <View className='true-price font-family-price'>
                              <Text className='font-family-price symbol'>￥</Text>
                              <Float value={item.price || 0} />
                            </View>
                            {!!item.market_price &&
                              <View className='price-right font-family-price'>￥{item.market_price || 0}</View>}
                          </View>
                        </View>
                      </View>
                    </View>
                  </AtSwipeAction>
                </View>
              </View>
              {edit && <View className='goodsum bottom'>
                <View onClick={this.checkAll.bind(this, index)} className='bottom_check'><Radio checked={item.checked}
                  color='#fe9f00'
                  value={item.id}
                /> 全选</View>
                <View className='sumbox'>
                  <View className='right' onClick={this.delcarall.bind(this, index)}>删除</View>
                </View>
              </View>}
            </View>)}
        </View>}
        <View style='height:50px'></View>
        {(list.length == 0) && loadMoreStatus != 'loading' && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/carnull.png`} mode='widthFix' />
          <View className='text'>收藏列表空空如也，<Text>去逛逛吧~</Text></View>
        </View>}

      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
